package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.config.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.mapper.RoleMapper;
import com.ktjiaoyu.crm.mapper.RoleRightMapper;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.RoleRight;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper,Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleRightMapper roleRightMapper;

    @Cacheable(value = "roleList",key = "'all'")
    @Override
    public List<Role> findAllRoles() {

        return roleMapper.selectList(null);
    }

    @Override
    public Page<Role> selectRolePages(Page page, String roleName) {
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        if(roleName != null && !"".equals(roleName)){
            queryWrapper.like("role_name",roleName);
        }

        return page.setRecords(roleMapper.selectRolePages(page,queryWrapper));
    }

    /**
     * 新增角色的同时保存角色权限
     * @param role
     * @param rightCodes
     * @return
     */
    @Override
    @Transactional
    public boolean saveRoleAndRight(Role role, String[] rightCodes) {
        //第一步：保存角色信息
        boolean resultOK = this.saveOrUpdate(role);
        //如果新增成功角色，则将权限信息也一起存入数据库中
        if(resultOK && role.getRoleId()!=null){
            //第二步：先删除旧的角色权限
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("rf_role_id",role.getRoleId());
            roleRightMapper.delete(updateWrapper);
        }
        //第三步：保存新的角色权限
        boolean roleRightOk = true;
        if(rightCodes!=null && rightCodes.length!=0){
            roleRightOk = roleRightMapper.saveRoleRight(role,rightCodes);
        }
        //清空所有用户权限缓存
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();

        return resultOK && roleRightOk;
    }

    @Override
    public Role findRoleByUserId(Long usrId) {

        return roleMapper.findRoleByUserId(usrId);
    }

}
